package org.smart.framework.core.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author lyric
 * @version 1.0.0
 * @date 2017/2/9 11:08
 * @description 类型转换工具类
 */
public final class CastUtil {

    private static final Logger logger = LoggerFactory.getLogger(CastUtil.class);

    /**
     * @author lyric
     * @description 转为 String 型
     * @param obj 转换对象
     * @return
     */
    public static String castString(Object obj) {
        return CastUtil.castString(obj, "");
    }

    /**
     * @author lyric
     * @description 转为 String 型(提供默认值)
     * @param obj 转换对象
     * @param defaultValue 默认值
     * @return
     */
    public static String castString(Object obj, String defaultValue) {
        return obj != null ? String.valueOf(obj) : defaultValue;
    }

    /**
     * @author lyric
     * @description 转为 long 型
     * @param obj 转换对象
     * @return
     */
    public static long castLong(Object obj) {
        return CastUtil.castLong(obj, 0);
    }

    /**
     * @author lyric
     * @description 转为 long 型(提供默认值)
     * @param obj 转换对象
     * @param defaultValue 默认值
     * @return
     */
    public static long castLong(Object obj, long defaultValue) {
        long longValue = defaultValue;
        if (null != obj) {
            String strValue = castString(obj);
            if (StringUtil.isNotEmpty(strValue)) {
                try {
                    longValue = Long.parseLong(strValue);
                } catch (NumberFormatException e) {
                    logger.error(e.getMessage(), e);
                    longValue = defaultValue;
                }
            }
        }
        return longValue;
    }
}
